import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {
    shopCarList: [],
    shopCarCount: 0,
    searchHistoryList: []
  },
  mutations: {
    setGoods(state, obj) {
      console.log(obj)
      var num = 0
      if (!state.shopCarList.some(v => v.id === obj.id)) {
        if (state.shopCarList.length === 0) {
          state.shopCarCount = obj.count
        }
        state.shopCarList.push(obj)
        return
      }
      state.shopCarList.find(v => v.id === obj.id).count += obj.count
      state.shopCarList.forEach(v => {
        num += v.count
      })
      state.shopCarCount = num
    },
    removeGoodsById(state, id) {
      var n = 0
      state.shopCarList = state.shopCarList.filter(v => v.id !== id)
      state.shopCarList.forEach(v => {
        n += v.count
      })
      state.shopCarCount = n
    },
    setSearchHistory(state, str) {
      if (state.searchHistoryList.some(v => v === str)) return
      state.searchHistoryList.push(str)
    },
    clearSearchHistory(state) {
      state.searchHistoryList = []
    }
  },
  actions: {
  },
  getters: {
    totalPrice(state) {
      var a = 0
      state.shopCarList.forEach(v => {
        a += v.price * v.count
      })
      return a
    }
  }
})
